/**
 * Created by rongyao on 2017/10/18.
 */
var mongoose = require('mongoose');
const Cate = require('../models/cate.model');

exports.create = function (req, res, next) {
	var cate = new Cate(req.body);
	cate.save().then(data => {
		res.json(data);
	});
}

exports.get = function (req, res, next) {
	var id = req.params.id;
	Cate.findById(id, function (err, data) {
		res.json(data);
	})
}

exports.update = function (req, res, next) {
	var id = req.params.id;
	Cate.findByIdAndUpdate(id, {$set: req.body}, {new: false})
		.then(data => {
			res.json(data);
		})
}


exports.remove = function (req, res, next) {
	var id = req.params.id;
	var ids=[];
	Cate.findOne({_id: id}, function(err, doc) {
		if(doc){
			doc.getChildren().then(function(docs){
				docs.push(doc);
				
				for (var i in docs) {
					ids.push(docs[i]._id);
				}
				Cate.remove({_id: {$in: ids}}).then(data=>{
					res.json({'msg':"删除成功",res:ids})
				})
			});
		}
	})

}

function reverseData(obj,pid){
	var result=[];
	var temp;
	var data = JSON.parse(JSON.stringify(obj));
	for(var i in data){
		if(data[i].parentId==pid){
			result.push(data[i]);
			temp = reverseData(data,data[i]._id);
			if(temp.length>0){
				data[i].children=temp;
			}
			
		}
	}
	return result;
}

exports.list = function (req, res, next) {
	Cate.find({},function (err,data) {
		var tree = reverseData(data,null);
		res.json(tree);
	})
}

exports.findIds = function (req, res, next) {
	var id = req.params.id;
	var ids=[];
	Cate.findOne({_id: id}, function(err, doc) {
		if(doc){
			doc.getChildren().then(function(docs){
				docs.push(doc);
				
				for (var i in docs) {
					ids.push(docs[i]._id);
				}
				res.json(ids);
			});
		}
	})
	
}